package fashionshop.gui.common.component;

import java.util.List;

import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableColumn;

import fashionshop.gui.common.model.ModelData;

@SuppressWarnings("serial")
public class DataGridView<E extends ModelData> extends JTable {
	
	private GridViewTableModel tableModel;
	
	
	@Override
	public void tableChanged(TableModelEvent e) {
		super.tableChanged(e);
		if(tableModel != null){
			List<ColumnConfig> columns = tableModel.getColumns();
			TableColumn tableColumn;
			ColumnConfig colConf;
			for(int i = 0; i < columns.size(); i++){
				colConf = columns.get(i);
				tableColumn = getColumnModel().getColumn(i);
				if(colConf.getWidth() != null){
					tableColumn.setPreferredWidth(colConf.getWidth());
				}
				if(colConf.getGridCellRenderer() != null){
					tableColumn.setCellRenderer(colConf.getGridCellRenderer());
				}
			}
		}
	}
	
	public DataGridView(){
		super();
		tableModel = new GridViewTableModel();
		setModel(tableModel);
	}
	
	public E getSelectedModel(){
		int row = getSelectedRow();
		return row >= 0 ? getModel(row) : null;
	}
	
	public int findModel(E model){
		return tableModel.findModel(model);
	}
	
	@SuppressWarnings("unchecked")
	public E getModel(int row){
		return (E) tableModel.getModel(row);
	}
	
	public void updateRow(E oldModel, E newModel){
		tableModel.updateRow(oldModel, newModel);
	}
	
	public void updateRow(E newModel, int row){
		tableModel.updateRow(newModel, row);
	}
	
	public void updateCurrentRow(E newModel){
		if(getSelectedRowCount() == 1){
			tableModel.updateRow(newModel, getSelectedRow());
		}
	}
	
	public void addRow(E model){
		tableModel.addRow(model);
	}
	
	public void insertRow(E model, int row){
		tableModel.insertRow(model, row);
	}
	
	@SuppressWarnings("unchecked")
	public void addRows(List<E> models){
		tableModel.addRows((List<ModelData>) models);
	}
	
	@SuppressWarnings("unchecked")
	public void insertRows(List<E> models, int row){
		tableModel.insertRows((List<ModelData>) models, row);
	}
	
	public void removeRow(E model){
		tableModel.removeRow(model);
	}
	
	public void removeRow(int row){
		tableModel.removeRow(row);
	}
	
	public void removeAllRow(){
		tableModel.removeAll();
	}

	@SuppressWarnings("unchecked")
	public List<E> getData() {
		return (List<E>) tableModel.getData();
	}
	
	@SuppressWarnings("unchecked")
	public void setData(List<E> models){
		tableModel.setData((List<ModelData>) models);
	}
	
	public void setColumnConfigs(List<ColumnConfig> columns){
		tableModel.setColumns(columns);
	}
	
}
